package 动态数组;

/*
* 动态数组
* */
public  class NewClassArray<E> {
    private  E [] data;
    /*size指向元素个数的下标*/
    private int size;
    /*动态改变数组大小
    *
    * */
    private void resize(int i) {
        E[] newData = (E[]) new Object[i];
        for (int j = 0; j < this.size; j++) {
            newData[j] = this.data[j];
        }
        data = newData;
    }
    public NewClassArray(){
        /*this调用构造函数*/
        this(10);
    }
    public NewClassArray(int capacity){
        this.data = (E[]) new Object[capacity];
        this.size = 0;
    }
    public int getSize(){
        return size;
    }
    public int getCapacity(){
        return this.data.length;
    }
    public boolean isEmpty(){
        return size == 0;
    }
    /*所有元素后添加元素*/
    public void addLast(E m){
        locateAdd(size, m);
    }
    /*头部添加元素*/
    public void addFirst(E m){
        locateAdd(0, m);
    }
    /*指定locate位置增加元素*/
    public void locateAdd(int locate, E m){
        if (locate< 0 || locate > size){
            throw new IllegalArgumentException("error");
        }
        if (size == this.getCapacity()){
            resize(2*this.getCapacity());
        }
        for (int i = this.size - 1; i >= locate; i--) {
            data[i+1] = data[i];
        }
        data[locate] = m;
        size++;
    }



    /*打印数组信息*/
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append(String.format("array: size = %d, capacity = %d\n", size, getCapacity()));
        builder.append("[");
        for (int i = 0; i < size; i++) {
            builder.append(data[i]);
            if (i + 1 != size){
                builder.append(",");
            }
        }
        builder.append("]");
        return builder.toString();
    }
    /*包含某个元素*/
    public boolean contains(E m){
        for (int i = 0; i < this.size; i++) {
            if (this.data[i].equals(m)){
                return true;
            }
        }
        return false;
    }
    /*寻找某个元素的索引*/
    public int search(E m){
        for (int i = 0; i < this.size; i++) {
            if (this.data[i].equals(m)){
                return i;
            }
        }
        return -1;
    }
    /*删除指定位置*/
    public E delete(int locate){
        if (locate< 0 || locate >= size){
            throw new IllegalArgumentException("error");
        }
        E res = data[locate];
        for (int i = locate+1; i <size; i++) {
            data[i-1] = data[i];
        }
        size--;
        data[size] = null;
        return res;
    }
    public E deleteLast(){
        return this.delete(size - 1);
    }
    public E deleteFirst(){
        return this.delete(0);
    }
    public E get(int index){
        if (index < 0 || index >= size){
            throw new IllegalArgumentException("error");
        }
        return data[index];
    }
    public E getLast(){
        return get(size - 1);
    }
    public E getFirst(){
        return get(0);
    }




}
